package cn.waka.sys.admin.dao;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.SelectKey;
import org.apache.ibatis.annotations.Update;

import cn.waka.sys.admin.object.Node;

@Mapper
public interface INodeDao {
    @Select("select node from s_system_node where is_auth=1")
    List<String> findAllURI();

    @Select("select id,node,title from s_system_node where is_auth=1")
    List<Node> findAll();

    @Select("select n.id,n.node,n.title from s_system_auth_node an left join s_system_node n on an.node_id=n.id where an.auth=#{authId}")
    List<Node> findByRoleId(int authId);

    @Insert("INSERT INTO s_system_node(node,title,create_at,pid,is_auth,is_menu)VALUES(#{node},#{title},#{createAt},#{pid},1,0)")
    @SelectKey(statement = "select last_insert_id()", keyProperty = "id", before = false, resultType = int.class)
    int insert(final Node node);

    @Select("select id,node,title,pid from s_system_node WHERE is_menu=1 and pid = 0")
    List<Node> getSelectNode();

    @Select("select id,node,title,is_menu,is_auth,pid from s_system_node WHERE pid=#{pid} and is_menu=1")
    List<Node> getSelectChildren(int pid);

    @Select("select id,node,title,is_menu as menu,is_auth as auth,pid from s_system_node order by pid")
    List<Node> getNodeList();

    @Select("select id,node,title,is_menu as isMenu,is_auth as isAuth,pid from s_system_node WHERE pid=#{pid}")
    List<Node> getChildrenList(int pid);

    @Select("select id,node,title,is_menu as isMenu,is_auth as isAuth,pid from s_system_node WHERE id=#{id}")
    Node getNodeById(int id);

    @Select("select id,node,title,is_menu as isMenu,is_auth as isAuth,pid from s_system_node WHERE node =#{node}")
    Node getNodeByUrl(String node);

    @Update("update s_system_node set title=#{title},is_auth=#{isAuth},is_menu=#{isMenu},pid=#{pid} where id=#{id}")
    int update(Node node);

    @Select("SELECT n.id,n.title,n.`node`,n.`pid`,IF(an.auth IS NULL,0,1) AS checked FROM  `s_system_node` n LEFT JOIN `s_system_auth_node` an ON n.id=an.node AND an.`auth`=#{roleId} WHERE n.`is_auth`=1")
    List<Node> getNodeTree(@Param("roleId") int roleId);

    @Delete("delete from s_system_auth_node where auth=#{roleId}")
    int delAll(String roleId);

    @Insert("INSERT INTO s_system_auth_node(auth,node)VALUES(#{roleId},#{node})")
    int insertAuthNode(@Param("roleId") String roleId, @Param("node") String node);
}
